package controllers.api;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import helper.PinduoduoHelper;
import models.Product;
import play.Logger;
import play.libs.WS;
import play.mvc.Controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class SynPinduoduoProducts extends Controller{

    public static final String PINDUODUO_V1_URL = "http://gw-api.pinduoduo.com/api/router";

    public static void synProducts() {

        Map<String , Object> params = new HashMap<>();
        params.put("type" , "pdd.ddk.goods.search");
        params.put("client_id" , PinduoduoHelper.CLIENT_ID);
        params.put("timestamp" , Long.toString(new Date().getTime()/1000));
        params.put("sort_type" , 0);
        params.put("page" , 2);
        params.put("page_size" , 10);
        params.put("with_coupon" , true);
        String sign = PinduoduoHelper.sgin(params);


        String url = PINDUODUO_V1_URL+ "?sign=" + sign;
        for (String key : params.keySet()) {
                url += "&"+ key+"="+params.get(key);
        }
        Logger.info("Url : %s" , url);
        WS.HttpResponse response = WS.url(url).timeout("500s").params(params).post();

        JsonObject searchResponse = response.getJson().getAsJsonObject();
        JsonObject searchTotal = searchResponse.get("goods_search_response").getAsJsonObject();
        JsonArray  goodsList = searchTotal.get("goods_list").getAsJsonArray();
        for(int i=0 ; i<goodsList.size(); i++) {
                JsonObject goodsDetail = goodsList.get(i).getAsJsonObject();
                Product product = Product.synProduct(goodsDetail);
                Logger.info("产品同步成功。GoodsId ： %s | goodsName : %s" , product.goodsId , product.goodsName);
        }
    }




}
